package fire.and.near.challenger.database;

import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import fire.and.near.challenger.database.limit.ChallengeConstraint;

public class DefaultChallengesManager {

	private static final String LAST_CHALLENGE_DATE = "lastChallengeDate";
	private static final String CHALLENGES_PICKED_COUNT = "challengesPickedCount";
	private static final int MAX_NUMBER_OF_CHALLENGES = 3;
	public static final String LAST_DEFAULT_CHALLENGE_ID = "lastDefaultChallengeId";

	public static boolean canGetDefaultChallenge(Activity context) {
		SharedPreferences sharedPrefs = context
				.getPreferences(Context.MODE_PRIVATE);
		long lastChallengeDate = sharedPrefs.getLong(LAST_CHALLENGE_DATE, -1);
		int challengesPickedCount = sharedPrefs.getInt(CHALLENGES_PICKED_COUNT,
				-1);

		if (lastChallengeDate != -1 && challengesPickedCount != -1) {
			Calendar lastChallenge = Calendar.getInstance();
			lastChallenge.setTimeInMillis(lastChallengeDate);
			Calendar today = Calendar.getInstance();
			today.setTimeInMillis(System.currentTimeMillis());
			if (lastChallenge.get(Calendar.DAY_OF_YEAR) == today
					.get(Calendar.DAY_OF_YEAR)
					&& lastChallenge.get(Calendar.YEAR) == today
							.get(Calendar.YEAR)) {
				if (challengesPickedCount <= MAX_NUMBER_OF_CHALLENGES) {
					Editor sharedPrefsEditor = sharedPrefs.edit();
					sharedPrefsEditor.putLong(LAST_CHALLENGE_DATE,
							today.getTimeInMillis());
					sharedPrefsEditor.putInt(CHALLENGES_PICKED_COUNT,
							challengesPickedCount + 1);
					sharedPrefsEditor.commit();
					return true;
				} else {
					return false;
				}
			} else {
				return true;
			}
		} else {
			return true;
		}
	}

	public static Long getLastDefaultChallengeId(Context context) {
		SharedPreferences sharedPrefs = context.getSharedPreferences(
				ChallengeConstraint.FILENAME, Context.MODE_PRIVATE);
		return sharedPrefs.getLong(LAST_DEFAULT_CHALLENGE_ID, 0);
	}

	public static void updateLastDefaultChallengeId(Context context,
			long challengeId) {
		SharedPreferences sharedPrefs = context.getSharedPreferences(
				ChallengeConstraint.FILENAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putLong(LAST_DEFAULT_CHALLENGE_ID, challengeId);
		editor.commit();
	}
}
